import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: Home,
    meta: {
      auth: false,
    },
  },
  {
    path: "/about",
    name: "about",
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue"),
    meta: {
      auth: false,
    },
  },
  {
    path: "/cart",
    name: "cart",
    component: () => import(/* webpackChunkName: "cart" */ "../views/Cart.vue"),
    meta: {
      auth: true,
    },
  },
  {
    path: "/preOrder",
    name: "preOrder",
    component: () =>
      import(/* webpackChunkName: "preOrder" */ "../views/PreOrder.vue"),
    meta: {
      auth: true,
    },
  },
  {
    path: "/profile",
    name: "profile",
    component: () =>
      import(/* webpackChunkName: "profile" */ "../views/Profile.vue"),
    meta: {
      auth: true,
    },
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "login" */ "../views/Login.vue"),
    meta: {
      auth: false,
    },
  },
  {
    path: "/search",
    name: "search",
    component: () =>
      import(/* webpackChunkName: "search" */ "../views/Search.vue"),
    meta: {
      auth: false,
    },
  },
  {
    path: "/csearch",
    name: "csearch",
    component: () =>
      import(/* webpackChunkName: "csearch" */ "../views/CatesSearch.vue"),
    meta: {
      auth: false,
    },
  },
  {
    path: "/detail/:id",
    name: "detail",
    component: () =>
      import(/* webpackChunkName: "detail" */ "../views/Detail.vue"),
    meta: {
      auth: false,
    },
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.meta.auth) {
    const token = localStorage.getItem("token") || undefined;
    if (token) next();
    else next(`/login?redirect=${to.path}`);
  } else {
    next();
  }
});

export default router;
